'use strict';

var jwt = require("jsonwebtoken");
/**
 * List of users
 */
exports.list = function(req, res) {
	req.getConnection(function(err, conn) {
        if (err) {
            return next(err);
        } else {
            conn.query("SELECT users.*,company.company_name FROM users LEFT JOIN company on users.company=company.id  ", [], function(err,result) {
                if (err) {
                    return next(err);
                } else {
                    res.json(result); //可以直接把结果集转化Json返回给客户端
                }
            });
        }
    });
};

/**
 * get of users
 */
exports.getuser = function(req, res) {
    data['id']=req.body.id;
    req.getConnection(function(err, conn) {
        if (err) {
            return next(err);
        } else {
            conn.query('select * from users where id=?', [data['id']], function(err,result) {
                if (err) {
                    return next(err);
                } else {
                    res.json(result); //可以直接把结果集转化Json返回给客户端
                }
            });
        }
    });
};
/**
 * 验证user
 */
exports.verifyUser = function(req, res) {
    var data = {};
    data['account']=req.body.account;
    data['password']=req.body.password;
    if (data['account'] == '' || data['password'] == '') {
        return res.send(401);
    }
    req.getConnection(function(err, conn) {
        if (err) {
            console.log(err);
            return res.send(401);
        } else {
            conn.query('select * from users where account=? and password=?',[data['account'],data['password']], function(err,result) {
                if (err) {
                    console.log(err);
                    return res.send(401);
                } else {
                    if(result.length>0){
                        console.log("登录成功:"+result[0]);
                        var authToken = jwt.sign(result[0], "secret");
                        return res.status(200).json({token: authToken,user:result[0]});
                    }else{
                        res.json("false");
                    }
                    // var token = jwt.sign(result[0], secret.secretToken, { expiresInMinutes: 60 });
                    // return res.json({token:token});
                    // res.json(result); //可以直接把结果集转化Json返回给客户端
                }
            });
        }
    });
};

/**
 * edit user
 */
exports.set = function(req, res) {
    var data = [];
    data=JSON.parse(req.body.jsonStr);
    var itemData=[];
    for(var item in data[0]){
        if(item!="id"){
            itemData.push(item);
        }
    }
    var sql="UPDATE users SET ";
    var lastObj="";
    itemData.forEach(function(val,index){
        lastObj=val;
    });
    itemData.forEach(function(itemVal,itemIndex){
        sql+=" "+itemVal+"= CASE id";
        data.forEach(function(val,index){
            sql+=" WHEN "+val.id+" THEN '"+val[itemVal]+"'";
        });
        if(itemIndex!=itemData.length-1){
            sql+=" END,";
        }else{
            sql+=" END ";
        }
    });
    sql+="WHERE id IN ("
    data.forEach(function(val,index){
        if(index!=data.length-1){
            sql+=val.id+",";
        }else{
            sql+=val.id+")";
        }
    });
    console.log(sql);
    req.getConnection(function(err, conn) {
        if (err) {
            return res.send(401);
        } else {
            conn.query(sql, function(err,result) {
                if (err) {
                    res.json(false);
                } else {
                    res.json(true);
                }
            });
        }
    });
};

/**
 * edit user
 */
exports.setuser = function(req, res) {
    var data = {};
    data=req.body;
    var sql="";
    if(JSON.stringify(data) != "{}"){
        var lastObj="";
        for (var prop in data){
            if(prop!="id"){
                lastObj=prop;
            }
        }
        for (var prop in data)
        {
            if(prop!="id"){
                sql+=" "+prop+"='"+data[prop]+"' ";
                if(prop!=lastObj){
                    sql+=" , ";
                }
            }
        }
        sql+="where id="+data['id'];
    }
    req.getConnection(function(err, conn) {
        if (err) {
            return res.send(401);
        } else {
            conn.query('UPDATE users SET '+sql, function(err,result) {
                if (err) {
                    res.json(false);
                } else {
                    res.json(true);
                }
            });
        }
    });
};

/**
 * del user
 */
exports.del = function(req, res) {
    var id=req.body.id;

    req.getConnection(function(err, conn) {
        if (err) {
            return res.send(401);
        } else {
            conn.query('DELETE FROM users WHERE id = '+id, function(err,result) {
                if (err) {
                    res.json(false);
                } else {
                    res.json(true); 
                }
            });
        }
    });
};

/**
 * add user
 */
exports.add = function(req, res) {
    var data = {};
    data=req.body;
    if(JSON.stringify(data) != "{}"){
        var sql="(";
        var lastObj="";
        for (var prop in data){
            lastObj=prop;
        }
        for (var prop in data)
        {
            sql+=prop;
            if(prop!=lastObj){
                sql+=" , ";
            }else{
                sql+=") values (";
            }
        }
        for (var prop in data)
        {
            sql+="'"+data[prop]+"' ";
            if(prop!=lastObj){
                sql+=" , ";
            }else{
                sql+=") ";
            }
        }
        req.getConnection(function(err, conn) {
            if (err) {
                return res.send(401);
            } else {
                conn.query('insert into users '+sql, function(err,result) {
                    if (err) {
                        res.json(false);
                    } else {
                        res.json(true); 
                    }
                });
            }
        });
    }else{
        res.json(false);
    }
};

